package org.example.seata.bs.auth.config;

import lombok.AllArgsConstructor;
import org.example.seata.common.security.config.auth.grant.CustomTokenGranter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenStore;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author hzq
 * @date 2021/12/6 14:52
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfiguration implements AuthorizationServerConfigurer {

    private final TokenStore tokenStore;
    private final PasswordEncoder passwordEncoder;
    private final UserDetailsService userDetailsService;
    private final AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // 系统
                .withClient("system")
                .secret(passwordEncoder.encode("system"))
                .scopes("all")
                .authorizedGrantTypes("password", "custom", "refresh_token", "authorization_code", "client_credentials")
                .autoApprove(false)
                .and()
                // 电脑端
                .withClient("pcSide")
                .secret(passwordEncoder.encode("pcSide"))
                .scopes("all")
                .authorizedGrantTypes("password", "custom", "refresh_token", "authorization_code", "client_credentials")
                .autoApprove(false)
                .and()
                // 移动端
                .withClient("mobileSide")
                .secret(passwordEncoder.encode("mobileSide"))
                .scopes("all")
                .authorizedGrantTypes("password", "custom", "refresh_token", "authorization_code", "client_credentials")
                .autoApprove(false);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenStore(tokenStore)
                .userDetailsService(userDetailsService)
                .authenticationManager(authenticationManager);
        setTokenGranter(endpoints);
    }

    private void setTokenGranter(AuthorizationServerEndpointsConfigurer endpoints) {
        TokenGranter defaultTokenGranter = endpoints.getTokenGranter();
        ArrayList<TokenGranter> tokenGranters = new ArrayList<>(Arrays.asList(defaultTokenGranter));
        CustomTokenGranter customTokenGranter =
                new CustomTokenGranter(
                        authenticationManager,
                        endpoints.getTokenServices(),
                        endpoints.getClientDetailsService(),
                        endpoints.getOAuth2RequestFactory()
                );
        tokenGranters.add(customTokenGranter);
        CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(tokenGranters);
        endpoints.tokenGranter(compositeTokenGranter);
    }
}
